import React, { FC, useState } from 'react';
import classnames from 'classnames';
import './index.less';

export interface RadioProps {
  data: { name: string; value: any; checked?: boolean }[];
  onClick?: (value) => void;
}

const Radio: FC<RadioProps> = (props) => {
  const { data, onClick } = props;
  const [radios, setRadis] = useState(data);

  // eslint-disable-next-line consistent-return
  const handleClick = (item) => {
    const newRadios = radios.map((it) => {
      if (it.value !== item.value) {
        return { ...it, checked: false };
      }
      return { ...it, checked: true };
    });

    setRadis(newRadios);
    if (typeof onClick === 'function') {
      return onClick(item);
    }
  };
  return (
    <div>
      {radios.map((item) => (
        <div
          className={classnames('selectList')}
          onClick={() => handleClick(item)}
          key={item.value}
        >
          <div className={classnames('selectItem')}>
            <span className={classnames('label')}>{item.name}</span>
            <i className={classnames({ active: item.checked })} />
          </div>
        </div>
      ))}
    </div>
  );
};

export default Radio;
